package mp

import (
	"context"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	xb "xorm.io/builder"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type NewsListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewNewsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewsListLogic {
	return &NewsListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *NewsListLogic) NewsList(req *types.NewsSearch) (resp *types.NewsList, err error) {
	var datas []models.News
	conds := xb.And(xb.Gt{"id": 0})
	if req.Keyword != "" {
		conds = conds.And(xb.Like{"title", "'%" + req.Keyword + "%'"})
	}
	if req.Cid != 0 {
		conds = conds.And(xb.Eq{"cid": req.Cid})
	}
	if req.IsUse != 0 {
		conds = conds.And(xb.Eq{"is_use": req.IsUse})
	}
	total := db.CountData(&models.News{}, conds)

	categories := db.CategoryMap()

	db.FindPageDatas(&datas, conds, req.Page)
	items := []types.News{}
	for _, v := range datas {
		tmp := types.News{}
		copier.Copy(&tmp, &v)
		tmp.CidName = categories[v.Cid].Title
		items = append(items, tmp)
	}
	return &types.NewsList{
		Total: int(total),
		Items: items,
	}, nil
}
